package org.dizena.common.trace.method;

import jakarta.annotation.Resource;
import org.dizena.common.trace.method.handler.MethodLogInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Order(13)
@Configuration
@EnableConfigurationProperties(MethodTraceAutoProperties.class)
@ConditionalOnProperty(
        prefix = "common.trace.method",
        value = {"enabled"},
        havingValue = "true"
)
public class MethodTraceAutoConfig implements CommandLineRunner {

    @Resource
    private MethodTraceAutoProperties properties;
    private ApplicationEventPublisher publisher;

    @Autowired
    public void setPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    private Logger logger = LoggerFactory.getLogger(MethodTraceAutoConfig.class);

    @Bean
    @ConditionalOnClass(value = {MethodLogInterceptor.class})
    public DefaultPointcutAdvisor defaultPointcutAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(properties.getPoint());
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(new MethodLogInterceptor(publisher));
        return advisor;
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("【自动化配置】---AOP Log 配置初始化");
    }
}
